import pyautogui
import time
import cv2
import numpy as np
from pynput import keyboard

# 全局控制开关
auto_fight_running = False

# 快捷键配置
KEY_BINDINGS = {
    'select': 'tab',
    'spell': '3',
    'physical': '2',
    'skill1': '4',
    'skill2': '5',
    'pickup': '`'
}

# 基础操作函数
def press_key(key):
    pyautogui.press(key)

def select_target():
    press_key(KEY_BINDINGS['select'])

def cast_spell():
    press_key(KEY_BINDINGS['spell'])

def physical_attack():
    press_key(KEY_BINDINGS['physical'])

def use_skill1():
    press_key(KEY_BINDINGS['skill1'])

def use_skill2():
    press_key(KEY_BINDINGS['skill2'])

def pickup():
    press_key(KEY_BINDINGS['pickup'])

# 目标检测
def has_target(template_path):
    try:
        template = cv2.imread(template_path)
        if template is None:
            print("无法加载模板图片")
            return False
            
        screenshot = pyautogui.screenshot()
        screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, _ = cv2.minMaxLoc(result)
        print(f"目标匹配值: {max_val:.2f}")
        return max_val > 0.7
    except Exception as e:
        print(f"目标检测错误: {str(e)}")
        return False

# 移动角色
# 角色在一定范围内跑动寻找怪物
def move_around():
    screen_width, screen_height = pyautogui.size()
    center_x, center_y = screen_width // 2, screen_height // 2
    directions = [
        (center_x, center_y - 500),  # 上
        (center_x, center_y + 500),  # 下
        (center_x - 500, center_y),  # 左
        (center_x + 500, center_y)   # 右
    ]
    for x, y in directions:
        if x < 0: x = 0
        if x >= screen_width: x = screen_width - 1
        if y < 0: y = 0
        if y >= screen_height: y = screen_height - 1
        pyautogui.click(x, y)
        time.sleep(2)
        select_target()
        time.sleep(0.5)

# 修改主循环
def auto_fight_loop():
    global auto_fight_running
    
    while auto_fight_running:
        select_target()
        time.sleep(0.5)
        
        print("开始攻击循环")
        attack_sequence()
        
        print("执行拾取操作")
        pickup()
        time.sleep(2)

# 攻击循环
def attack_sequence():
    # 法术攻击阶段
    for _ in range(15):
        if not auto_fight_running:
            return
        cast_spell()
        time.sleep(1)
    
    # 物理攻击阶段
    for _ in range(5):
        if not auto_fight_running:
            return
        physical_attack()
        time.sleep(1)
    
    # 技能阶段
    press_key('2')
    time.sleep(5)
    use_skill2()
    time.sleep(2)
    use_skill1()

# 主循环
def auto_fight_loop(template_path):
    global auto_fight_running
    
    while auto_fight_running:
        # 尝试选择目标
        select_target()
        time.sleep(0.5)
        
        if has_target(template_path):
            print("开始攻击循环")
            while has_target(template_path) and auto_fight_running:
                attack_sequence()
            
            # 确保怪物死亡后拾取物品
            print("执行拾取操作")
            # for _ in range(3):  # 尝试拾取3次
            #     pickup()
            #     time.sleep(2)
            pickup()
            time.sleep(2)
        else:
            print("寻找目标...")
            move_around()

# 键盘控制
def on_press(key):
    global auto_fight_running
    try:
        if key == keyboard.Key.f3:
            auto_fight_running = not auto_fight_running
            print("自动打怪已" + ("启动" if auto_fight_running else "停止"))
    except:
        pass

# 主函数
def main():
    # 启动监听
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    
    # 模板路径
    template_path = r"E:\Private.Net\WorkShop\tqsdk\Tq\Lab\PyQt\health_bar_template.png"
    
    print("按F3开始/停止自动打怪")
    try:
        while True:
            if auto_fight_running:
                auto_fight_loop(template_path)
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("程序退出")

if __name__ == "__main__":
    main()